package com.shd.edanpei.customer.presenter;

import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.shd.edanpei.R;
import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.dialog.DialogUtil;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.bean.OrderListModel;
import com.shd.edanpei.bean.StatusBean;
import com.shd.edanpei.bean.UrlModel;
import com.shd.edanpei.customer.activity.PayActivity;
import com.shd.edanpei.customer.contract.CMainContract;
import com.shd.edanpei.enums.StatusEnum;
import com.shd.edanpei.enums.UrlEnum;
import com.shd.edanpei.util.ToastUtil;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/9/27.
 * yang-wen-wen
 */

public class CMainPresenter extends BasePresenterImpl<CMainContract.CMainIView>
        implements CMainContract.CMainIPresenter {

    public CMainPresenter(CMainContract.CMainIView mView) {
        super(mView);
    }

    @Override
    public void search(String orderNo) {
        mBaseIView.showLoading("");
        ApiCreator.getApi().searchOrder(orderNo, true)
                .compose(RxTransformer.<List<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<OrderListModel>>() {
                    @Override
                    protected void onSuccess(List<OrderListModel> data) {
                        if (data != null && data.size() > 0) {
//                            if (TextUtils.isEmpty(data.get(0).getLoanCreditPath())) {
//                                //未授权
//                                getH5(data);
//                            } else {
//                                //已授权
//                                mBaseIView.getAdapter().setNewData(data);
//                            }

                            mBaseIView.getAdapter().setNewData(data);

                        } else {
                            mBaseIView.getAdapter().setNewData(null);
                            mBaseIView.getAdapter().setEmptyView(getNullLayout("暂无搜索结果"));
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getAdapter().setEmptyView(getNullLayout("暂无搜索结果"));
                    }

                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
    }


    /**
     * 检查是否授权
     */
    public void checkAuthorization(OrderListModel model, Bundle bundle) {

        if (TextUtils.isEmpty(model.getLoanCreditPath())) {
            //未授权
            getH5(model,bundle);
        } else {
            //已授权
            mBaseIView.startActivity(PayActivity.class, bundle);
        }


    }

    public void getH5(final OrderListModel model, final Bundle bundle) {
        ApiCreator.getApi().getUrl(UrlEnum.f.getType())
                .compose(RxTransformer.<UrlModel>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UrlModel>() {
                    @Override
                    protected void onSuccess(UrlModel data) {
                        showDialog(data.getUrlShow(), model,bundle);

                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        super.onFailure(throwable);

                    }
                });
    }

    private void showDialog(String url, final OrderListModel model, final Bundle bundle) {
        View view = LayoutInflater.from(mBaseIView.getContext()).inflate(R.layout.dialog_authorized, null);
        WebView webView = view.findViewById(R.id.webview);
        final ProgressBar progressBar = view.findViewById(R.id.progressBar);
        TextView tvDone = view.findViewById(R.id.done);
        final Dialog dialog = new Dialog(mBaseIView.getContext(), R.style.dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        webView.loadUrl(url);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView webView, int i) {
                if (i == 100) {
                    progressBar.setVisibility(View.GONE);
                }
                super.onProgressChanged(webView, i);
            }

        });
        tvDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmAuthoriz(model,bundle);
                dialog.dismiss();
            }

        });

        dialog.show();
    }

    private void confirmAuthoriz(final OrderListModel model, final Bundle bundle) {
        ApiCreator.getApi().confirmAuthoriz(model.getOrderId())
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {
                        DialogUtil.hintDialog(mBaseIView.getContext(), R.drawable.ic_success2, "授权成功");
                        model.setLoanCreditPath("123");
                        mBaseIView.startActivity(PayActivity.class, bundle);
                    }
                });
    }

    @Override
    public void search() {
        ApiCreator.getApi().searchOrder(false)
                .compose(RxTransformer.<List<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<OrderListModel>>() {
                    @Override
                    protected void onSuccess(List<OrderListModel> data) {
                        if (data != null && data.size() > 0) {
                            mBaseIView.getAdapter().setNewData(data);
                        } else {
                            mBaseIView.getAdapter().setNewData(null);
                            mBaseIView.getAdapter().setEmptyView(getNullLayout("暂无订单记录"));
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getAdapter().setEmptyView(getNullLayout("暂无订单记录"));
                    }

                    @Override
                    public void onFinish() {
                        mBaseIView.getRefreshLayout().setRefreshing(false);
                    }
                });
    }

    private View getNullLayout(String str) {
        View view = LayoutInflater.from(mBaseIView.getContext()).inflate(R.layout.null_layout_c, null);
        ((TextView) view.findViewById(R.id.tv_hint)).setText(str);
        return view;
    }


    @Override
    public void sureGetLone(final int orderID, final int orderType, final int index) {
//        final int orderID = bundle.getInt(Constant.ORDER_ID);
//        final int orderType = bundle.getInt(Constant.ORDER_TYPE);
//        final int index = bundle.getInt(Constant.INDEX);
        DialogUtil.infoDialog(mBaseIView.getContext(), "立即确认", "请务必确认您已收到终审金额", null, null, new DialogUtil.SureListener() {
            @Override
            public void sure() {
                mBaseIView.showLoading("");
                ApiCreator.getApi().sureGetLoan(orderID, orderType)
                        .compose(RxTransformer.<NoDataResponse>errorHandle())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<NoDataResponse>() {
                            @Override
                            protected void onSuccess(NoDataResponse data) {
                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.success.getStatus()));
                                DialogUtil.hintDialog(mBaseIView.getContext(), R.drawable.ic_success, "确认成功");
                            }

                            @Override
                            public void onFinish() {
                                mBaseIView.stopLoading();
                            }
                        });
            }
        });

    }
}
